const tools = require("./tools");
const local = require("./forLocalItems");
const Option = require("./Option");

class LocalOptions{
    constructor( localName , defData ){
        if(!localName) return null;
        this._def = defData || { ver:1.0 };
        this._def.ver  = this._def.ver || 1.0;

        this.__localName = localName;
        this._data = null;
        this._readLoacal();
    }

    getLocalName(){
        return this.__localName;
    }

    hasKey( key ){
        return !tools.isType( this._data[key] , "Undefined");
    }

    getRef(){
        let keys = Array.prototype.slice.call(arguments);
        let key = keys[0] , ref = this._data;

        if(key){
            ref = (ref[keys[0]] && ref[keys[0]].getRef ) ? ref[keys[0]].getRef( ...Array.prototype.slice.call(keys , 1) ) : null;
        }else{
            ref = this;
        }

        return ref;
    }

    get( key , assign ){
        let v;
        if( !key ){
            v = assign ? this : this._getData();
        }else{
            v = this._data[key] && this._data[key].get ? this._data[key].get() : this._data[key];
        }
        return v;
    }

    _readLoacal(){
        if(!this._data){
            this._data = {};
            let save=false;
            let d = local.get( this.__localName );
            if(tools.isType( d , 'String') && d ){
                d = d ? JSON.parse(d) : d;
            }
            if(!d || ( d.ver != this._def.ver )){
                //默认数值
                d = this._def.upgrade ? this._def.upgrade( d )  : d;
                d = d ? d : Object.assign({} , this._def);
                d.ver = this._def.ver;
                save = true;
            }
            for( let key in d){
                if( tools.isType(d[key] , "Function") ) continue;
                if( key == 'ver' ){
                    this._data[key] = d[key];
                }else{
                    this._data[key] = new Option( key , d[key] , tools.type(d[key]) , this );
                }
            }
            if(save) this.save();
        }
    }

    save(){
        local.set(this.__localName , this._getData() );
    }

    _getDefData(){

    }

    _getData(){
        let d = {};
        for(let key in this._data){
            d[key] = this._data[key].get ? this._data[key].get() : this._data[key];
        }
        return d;
    }
}

module.exports = LocalOptions; 